package com.springboot.demo.common.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.lang3.StringUtils;

public class MD5Utils {
	public static String formatUpper32(String plainText) {
		String buf = format32(plainText);
		return buf.toUpperCase();
	}
	
	public static String format32(String plainText) {
		String buf = format(plainText);
		return buf;
	}
	
	public static String format16(String plainText) {
		String buf = format(plainText);
		return buf.substring(8, 24);
	}
	
	public static String format(String plainText) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(plainText.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			return buf.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	
    /**
     * @MethodName:getMD5
     * @Author JuoChiu
     * @Date 2017年12月6日 下午4:26:39
     * @Description:向getMD5方法传入一个你需要转换的原始字符串,将返回字符串的MD5码
     * @param str 原始字符串
     * @return 返回字符串的MD5码
     * @ReturnType String
     */
	@SuppressWarnings("all")
    public static String getMD5(String str) {
        if (StringUtils.isNotEmpty(str)) {
            MessageDigest digest = null;
            try {
                digest = MessageDigest.getInstance("MD5");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            if (digest != null) {
                byte[] bytes = str.getBytes();
                byte[] results = digest.digest(bytes);
                StringBuilder sb = new StringBuilder();
                for (byte result : results) {
                    // 将byte数组转化为16进制字符存入StringBuilder中
                    sb.append(String.format("%02x", result));
                }
                return sb.toString();
            }
        }
        return null;
    }
    
	public static void main(String[] args) {
		System.out.println(format32("12345613628420127"));
	}
}
